import React, {useEffect, useMemo} from "react"
import {createEmployee} from "../apis/EmployeeApi";
import {Col, Form, FormInstance, FormProps, Input, Row, Select} from "antd";
import {NumberIdAndName} from "../types/BasicModels";

export interface EditEmployeeFormProps {
    initialData?: EmployeeFormData
    roles: Array<NumberIdAndName>
    onFinish: FormProps<EmployeeFormData>["onFinish"]
    loading: boolean
    form: FormInstance<EmployeeFormData>
}

export interface EmployeeFormData {
    name: string
    phoneNumber: string
    roleIds: number[]
    password?: string
}

const EditEmployeeForm: React.FC<EditEmployeeFormProps> = (props) => {
    const isEdit = useMemo(() => {
        if (props.initialData)
            props.form.setFieldsValue(props.initialData)
        return !!props.initialData
    }, [props.initialData,props.form]);
    return (
        <Form<EmployeeFormData>
            layout={"vertical"}
            form={props.form}
            onFinish={props.onFinish}>
            <Row gutter={16}>
                <Col span={12}>
                    <Form.Item name={"name"} label={"姓名"} rules={[{required: true}]}>
                        <Input/>
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item name={"roleIds"} label={"角色"} rules={[{
                        required: true
                    }]}>
                        <Select placeholder={"选择角色"} mode={"multiple"}>
                            {props.roles.map(role => {
                                return <Select.Option key={role.id} value={role.id}>{role.name}</Select.Option>
                            })}
                        </Select>
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item name={"phoneNumber"} label={"手机号"} rules={[{required: true}]}>
                        <Input/>
                    </Form.Item>
                </Col>
                {!isEdit ? <Col span={12}>
                    <Form.Item name={"password"} label={"密码"} rules={[]}>
                        <Input placeholder={"不填写将自动生成"}/>
                    </Form.Item>
                </Col> : undefined}
            </Row>
        </Form>
    )
}

export default EditEmployeeForm
